/**
 * 全局自定义指令
 *
 * 1、v-debounce         输入框防抖指令    入参：callback回调函数     <input v-debounce="inputFn" placeholder="请输入" v-model="inputValue" />
 * 2、v-throttle         点击按钮防抖      入参：callback回调函数     <button v-throttle="btnFn">点击按钮时，节流</button>
 * 3、v-permission       权限校验指令      入参：无
 * */
import store from '@/store'
import { Notify } from 'vant'

// 防抖
const debounce = {
  mounted(el, binding) {
    if (typeof binding.value !== 'function') {
      console.error('Please enter a function')
      return
    }
    let timer = null
    el.addEventListener('input', () => {
      timer && clearTimeout(timer)
      timer = setTimeout(() => {
        binding.value()
      }, 1000)
    })
  }
}

// 节流
const throttle = {
  mounted(el, binding) {
    if (typeof binding.value !== 'function') {
      console.error('Please enter a function')
      return
    }
    let timer, timer_end
    el.addEventListener('click', () => {
      if (timer) {
        Notify({ type: 'warning', message: '点击频率过快' })
        clearTimeout(timer_end)
        return (timer_end = setTimeout(() => binding.value(), 2000))
      }
      binding.value()
      timer = setTimeout(() => (timer = null), 2000)
    })
  }
}

// 权限验证
const permission = {
  mounted(el, binding) {
    // let btnRoles = router.currentRoute.value.meta.roles // 当前路由的权限列表
    const roles = store.user.roles
    const btnRoles = binding.value
    if (btnRoles && btnRoles instanceof Array && btnRoles.length > 0) {
      const hasPermission = roles.some(role => btnRoles.includes(role))
      if (!hasPermission) el.parentNode && el.parentNode.removeChild(el) // 没有权限 移除Dom元素
    } else {
      throw new Error('need roles! Like v-permission')
    }
  }
}

const directivesObj = {
  debounce,
  throttle,
  permission
}

export default function directives(app) {
  Object.keys(directivesObj).forEach(v => app.directive(v, directivesObj[v]))
}
